//
//  ViewController.swift
//  Couter
//
//  Created by huangguojian on 2021/11/26.
//

import UIKit

class ViewController: UIViewController {

    private let countLb = UILabel()
    private let addOneBtn = UIButton()
    private let minusOneBtn = UIButton()
    
    private var count: Int = 0 {
        willSet {
            countLb.text = String(newValue)
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initViews()
        setTargets()
    }
    
    private func initViews() {
        
        //控件样式设置
        
        countLb.text = String(count)
        countLb.textColor = .black
        countLb.sizeToFit()
        
        addOneBtn.setTitle("+1", for: .normal)
        addOneBtn.backgroundColor = .blue
        
        minusOneBtn.setTitle("-1", for: .normal)
        minusOneBtn.backgroundColor = .red
        
        let btnStackView: UIStackView = {
            let v = UIStackView(arrangedSubviews: [addOneBtn, minusOneBtn])
            v.axis = .horizontal
            v.spacing = 8
            v.distribution = .fillEqually
            return v
        }()
        
        let bgStackView: UIStackView = {
            let v = UIStackView(arrangedSubviews: [countLb, btnStackView])
            v.axis = .vertical
            v.spacing = 8
            v.alignment = .center
            v.translatesAutoresizingMaskIntoConstraints = false
            return v
        }()
        
        //控件载入主View
        self.view.addSubview(bgStackView)
        
        //布局约束
        bgStackView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
        bgStackView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true
        btnStackView.widthAnchor.constraint(equalToConstant: 160).isActive = true
        btnStackView.heightAnchor.constraint(equalToConstant: 40).isActive = true
        
        
    }
    
    private func setTargets() {
        
        addOneBtn.addTarget(self, action: #selector(addOne), for: .touchUpInside)
        minusOneBtn.addTarget(self, action: #selector(minusOne), for: .touchUpInside)
    }
    
    @objc private func addOne() {
        count += 1
    }
    
    @objc private func minusOne() {
        count -= 1
    }
}
